package com.dd.cloud.common.annotate.validation.impl;

import com.dd.cloud.common.annotate.validation.Url;
import com.dd.cloud.common.constants.RegularConstants;
import com.dd.cloud.common.utils.RegexUtils;
import org.apache.commons.lang3.StringUtils;
import org.hibernate.validator.constraintvalidation.HibernateConstraintValidatorContext;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;

/**
 * url地址, 文件链接地址
 *
 * @author zk
 */
public class UrlValidation implements ConstraintValidator<Url, Object> {
    private Url url;

    @Override
    public void initialize(Url urlVal) {
        url = urlVal;
    }

    @Override
    public boolean isValid(Object value, ConstraintValidatorContext context) {
        String ph = (String) value;
        if (!url.required() && StringUtils.isBlank(ph)) {
            return true;
        }
        if (url.required() && StringUtils.isBlank(ph)) {
            return false;
        }
        //如果设置的返回的消息参数信息,则替换参数
        if (!StringUtils.isBlank(url.begin())){
            context.unwrap( HibernateConstraintValidatorContext.class ).addMessageParameter( "begin", url.begin() );
        }
        return RegexUtils.regCheck(ph, RegularConstants.URL_REGEXP);
    }
}
